import base64
import pickle
from django.http import JsonResponse

from django_redis import get_redis_connection


def merge_cookie_to_redis(request, response):
    cookie_carts = request.COOKIES.get('carts')
    user_id = request.user.id

    if cookie_carts:
        carts = pickle.loads(base64.b64decode(cookie_carts))  # type: dict
        # 初始化一个字典  用于保存  sku_id: count
        cookie_dict = dict()
        # 初始化一个列表用于保存选中的商品id
        selected_ids = list()
        # 初始化一个列表用于保存未选中的商品id
        unselected_ids = list()

        for sku_id, count_selected_dict in carts.items():
            cookie_dict[sku_id] = count_selected_dict['count']

            if count_selected_dict['selected']:
                selected_ids.append(sku_id)
            else:
                unselected_ids.append(sku_id)

        redis_cli = get_redis_connection('carts')
        pipeline = redis_cli.pipeline()

        pipeline.hmset(f'carts_{user_id}', cookie_dict)
        if selected_ids:
            #  *selected_ids  对列表数据进行解包
            pipeline.sadd(f'selected_{user_id}', *selected_ids)

        if unselected_ids:
            pipeline.srem(f'selected_{user_id}', *unselected_ids)

        pipeline.execute()
    response.delete_cookie('carts')


